package com.zzyl.common.utils.huawei;

import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.dto.DeviceDto;
import com.zzyl.common.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2025/2/28 18:32
 */
@Slf4j
@Component
public class HuaweiIotUtil {
    @Autowired
    private IoTDAClient client;

    /**
     * 1、查询华为IOT物联网产品列表
     */
    public List<ProductSummary> queryProductList() {
        // 1、构建请求
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        listProductsRequest.setLimit(50);

        // 2、发起请求
        ListProductsResponse response;
        try {
            response = client.listProducts(listProductsRequest);
        } catch (Exception e) {
            log.error("物联网接口 - 查询产品列表，同步失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询产品列表，同步失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.error("物联网接口 - 查询产品列表，同步失败");
            throw new BaseException("物联网接口 - 查询产品列表，同步失败");
        }
        return response.getProducts();
    }

    /**
     * 2、添加设备
     */
    public String addDevice(DeviceDto deviceDto) {
        // 1、构建请求
        AddDeviceRequest request = new AddDeviceRequest();

        AddDevice body = new AddDevice();
        // 产品ID
        body.withProductId(deviceDto.getProductKey());
        // 设备标识码
        body.withNodeId(deviceDto.getNodeId());
        // 设备名称
        body.withDeviceName(deviceDto.getDeviceName());
        // 设备描述
        body.withDescription(deviceDto.getDeviceName());

        AuthInfo authInfo = new AuthInfo();
        // 设备秘钥
        authInfo.withSecret(deviceDto.getSecret());
        body.setAuthInfo(authInfo);

        request.withBody(body);

        // 2、发起请求
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            log.error("物联网接口 - 注册设备，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.error("物联网接口 - 注册设备，调用失败");
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        return response.getDeviceId();
    }

    /**
     * 3、删除设备
     * @param deviceId iot设备ID
     */
    public void removeDevice(String deviceId) {
        // 1、构建请求对象
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(deviceId);

        // 2、发起请求
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            log.error("物联网接口 - 删除设备，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.error("物联网接口 - 删除设备，调用失败");
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
    }

    /**
     * 4、查询设备详情
     * @param deviceId iot设备ID
     * @return
     */
    public ShowDeviceResponse queryDeviceDetail(String deviceId) {
        // 1、构建请求对象
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(deviceId);

        // 2、发起请求
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.info("物联网接口 - 查询设备详情，调用失败");
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        return response;
    }

    /**
     * 5、查询设备最近一次上报的数据（设备影子数据）
     * @param deviceId iot设备ID
     * @return
     */
    public List<DeviceShadowData> queryDeviceShadowData(String deviceId) {
        // 1、构建请求对象
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(deviceId);

        // 2、发起请求
        ShowDeviceShadowResponse response;

        try {
            response = client.showDeviceShadow(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备上报数据，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.info("物联网接口 - 查询设备上报数据，调用失败");
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }

        // 3、解析结果
        List<DeviceShadowData> shadow = response.getShadow();
        return shadow;
    }

    /**
     * 6、修改设备信息
     * @param iotId iot设备ID
     * @param deviceName 设备名称
     */
    public void updateDeviceInfo(String iotId, String deviceName) {
        // 1、构建请求对象，更新设备信息
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(iotId);
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceName);
        body.withDescription(deviceName);
        request.withBody(body);

        // 2、发起请求
        UpdateDeviceResponse response;
        try {
            response = client.updateDevice(request);
        } catch (Exception e) {
            log.error("物联网接口 - 修改设备，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.error("物联网接口 - 修改设备，调用失败");
            throw new BaseException("物联网接口 - 修改设备，调用失败");
        }
    }

    /**
     *  7、查询产品详情
      * @param productId 产品ID
     * @return 产品详情集合
     */
    public List<ServiceCapability> queryProductDetail(String productId) {
        // 1、构建请求对象，调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productId);
        ShowProductResponse response;

        // 2、发起请求
        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            log.error("物联网接口 - 查询产品详情失败，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 -  查询产品详情失败");
        }

        if (!Integer.valueOf(response.getHttpStatusCode()).toString().startsWith("2")) {
            log.error("物联网接口 - 查询产品详情失败，调用失败");
            throw new BaseException("物联网接口 -  查询产品详情失败");
        }

        // 3、返回数据
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        return serviceCapabilities;
    }
}